package guanqu.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import com.alibaba.fastjson.JSON;

import guanqu.beans.HistoryIrrBRWaterDam;
import guanqu.beans.RealTimeIrrBRWaterDam;
import manager.PersistentManager;
import manager.Utils;

/**
 * Servlet implementation class GetHistoryWaterGateDam
 */
// @WebServlet("/GetHistoryWaterGateDam")
public class GetHistoryWaterGateDam extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static final int MAX = 1;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetHistoryWaterGateDam() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");

		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data, Upload.class);

		Download download = new Download();

		// 测站编码
		String stadiaCode = upload.getStadiaCode();

		String cleanTime = upload.getDate();
		// 若是今天
		if (Utils.isToday(cleanTime)) {

			// 下限时间
			Calendar downtime = Utils.getCalendarByStr(cleanTime + " 00:00:00");
			// 上限时间
			Calendar uptime = Utils.getCalendarByStr(cleanTime + " 24:00:00)");

			if (upload.getFirst() != 0) {
				downtime = Utils.fromL(upload.getStamp());
			}
			SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
			// Session session = sf.openSession();
			Session session = sf.getCurrentSession();

			Transaction tx = session.beginTransaction();
			try {
				// 获取闸门实时数据
				Query q = session.createQuery(
						"select new RealTimeIrrBRWaterDam(meaTime,heightUp,heightDown,fluxGate) from RealTimeIrrBRWaterDam Dam where Dam.stadiaCode=? and Dam.meaTime > ? and Dam.meaTime < ? order by Dam.meaTime asc ");
				q.setParameter(0, stadiaCode);
				q.setParameter(1, downtime);
				q.setParameter(2, uptime);

				q.setMaxResults(MAX);

				List<RealTimeIrrBRWaterDam> realTimeIrrBRWaterDams = q.list();

				List<HistoryIrrBRWaterDam> historyIrrBRWaterDams = new ArrayList<HistoryIrrBRWaterDam>();
				for (RealTimeIrrBRWaterDam d : realTimeIrrBRWaterDams) {
					HistoryIrrBRWaterDam historyIrrBRWaterDam = new HistoryIrrBRWaterDam();
					BeanUtils.copyProperties(historyIrrBRWaterDam, d);
					historyIrrBRWaterDams.add(historyIrrBRWaterDam);
				}
				download.dams = historyIrrBRWaterDams;

				tx.commit();
				download.status = DownloadInfo.SUCCESS;
			} catch (Exception e) {
				download.status = DownloadInfo.FAILED;
				tx.rollback();
				e.printStackTrace();
			} finally {
				// session.close();
			}

		}
		// 若是以前
		else if (Utils.compareTime(cleanTime) < 0) {

			// 下限时间
			Calendar downtime = Utils.getCalendarByStr(cleanTime + " 00:00:00");
			// 上限时间
			Calendar uptime = Utils.getCalendarByStr(cleanTime + " 24:00:00)");

			if (upload.getFirst() != 0) {
				downtime = Utils.fromL(upload.getStamp());
			}
			SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
			// Session session = sf.openSession();
			Session session = sf.getCurrentSession();

			Transaction tx = session.beginTransaction();
			try {
				// 获取闸门实时数据
				Query q = session.createQuery(
						"select new HistoryIrrBRWaterDam(meaTime,heightUp,heightDown,fluxGate) from HistoryIrrBRWaterDam Dam where Dam.stadiaCode=? and Dam.meaTime > ? and Dam.meaTime < ? order by Dam.meaTime asc ");
				q.setParameter(0, stadiaCode);
				q.setParameter(1, downtime);
				q.setParameter(2, uptime);
				q.setMaxResults(MAX);

				download.dams = q.list();

				tx.commit();
				download.status = DownloadInfo.SUCCESS;
			} catch (Exception e) {
				download.status = DownloadInfo.FAILED;
				tx.rollback();
				e.printStackTrace();
			} finally {
				// session.close();
			}

		}
		// 若是以后
		else {
			download.setStatus(DownloadInfo.FAILED);
		}

		response.setCharacterEncoding("UTF-8");
		System.out.println(JSON.toJSONString(download));
		response.getWriter().append(JSON.toJSONString(download));

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	// 上行数据
	public static class Upload {
		// 测站编码
		String stadiaCode;

		// 查询时间，某一天
		String date;

		// 是否是第一次
		int first;// 0 第一次;其他不是

		// 开始的时间戳
		long stamp;

		public String getStadiaCode() {
			return stadiaCode;
		}

		public void setStadiaCode(String stadiaCode) {
			this.stadiaCode = stadiaCode;
		}

		public String getDate() {
			return date;
		}

		public void setDate(String date) {
			this.date = date;
		}

		public int getFirst() {
			return first;
		}

		public void setFirst(int first) {
			this.first = first;
		}

		public long getStamp() {
			return stamp;
		}

		public void setStamp(long stamp) {
			this.stamp = stamp;
		}

	}

	// 下行数据
	public static class Download {

		int status;
		List<HistoryIrrBRWaterDam> dams = new ArrayList<>();

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}

		public List<HistoryIrrBRWaterDam> getDams() {
			return dams;
		}

		public void setDams(List<HistoryIrrBRWaterDam> dams) {
			this.dams = dams;
		}

	}

	@Test
	public void test1() {
		// 测站编码
		String stadiaCode = "10510001";

		String str_down = "2013-09-08 00:00:00";
		String str_up = "2013-09-08 24:00:00";

		// 下限时间
		Calendar downtime = Utils.getCalendarByStr(str_down);
		// 上限时间
		Calendar uptime = Utils.getCalendarByStr(str_up);
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		Session session = sf.openSession();

		Transaction tx = session.beginTransaction();
		try {
			// 获取闸门实时数据
			Query q = session.createQuery(
					"from HistoryIrrBRWaterDam Dam where Dam.stadiaCode=? and Dam.meaTime > ? and Dam.meaTime < ? order by Dam.meaTime asc ");
			// Query q = session.createQuery("from HistoryIrrBRWaterDam Dam
			// where Dam.stadiaCode=? order by Dam.meaTime asc ");
			q.setParameter(0, stadiaCode);
			q.setParameter(1, downtime);
			q.setParameter(2, uptime);

			List l = q.list();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
